const is_online = true
const common = {
    is_online: is_online,
    // 资源图片域名
    image_resource: 'https://img.ameimeika.com/h5_images/mp_images',
    // 接口图片域名
    image_response: 'https://img.ameimeika.com/',
    // php接口请求域名
    base_url: is_online
        ? 'https://app.ameimeika.com/':'http://test.api2.ameimeika.com/',
        // : 'https://mp.ameimeika.com/',
    // java接口域名
    java_base_url: is_online
        ? 'https://openapi.ameimeika.com/'
        : 'https://mpingtest.ameimeika.com/',
    // 预上线
    // : 'https://app2.ameimeika.com/',
    // 签到地址
    sign_in_url: is_online
        ? 'https://h5.ameimeika.com/sign_in_3.0/index.html'
        : 'https://h5.ameimeika.com/sign_in_3.0/index.html',

    // 生美H5地址
    life_beauty: is_online ? "https://h5.ameimeika.com/life_beauty/#/" : "https://h5s.ameimeika.com/life_beauty/#/",
    // 请求方法
    fly_post (path, data = {}, callback_success, isJava) {
        /**
         * 网络请求方法
         * path:请求地址
         * data:请求参数
         * callback_success:请求成功回调，用参数接收返回值
         */
        let Fly = require('flyio/dist/npm/wx')
        let fly = new Fly()
        let that = this
        fly.config = {
            method: 'POST', //请求方法， GET 、POST ...
            headers: {
                'Authorization': '',
                'appVersion': '3.0',
                'appSystem': 'minapp',
                'content-type': 'application/json'
            },
            // 请求头
            baseURL: !isJava ? common.base_url : common.java_base_url, //请求基地址
            //是否自动将Content-Type为“application/json”的响应数据转化为JSON对象，默认为true
            parseJson: true,
            timeout: '10000' //超时时间
        }
        // 请求拦截器
        fly.interceptors.request.use(request => {
            request.timeout = 30000
            if (wx.getStorageSync('user_token')) {
                //检查本地缓存是否有token存在没有则重新获取
                request.headers = {
                    //设置请求头
                    'Authorization': 'Bearer ' + wx.getStorageSync('user_token'),
                    'content-type': 'application/json',
                }
                return request
            }
        })
        // 响应拦截器
        fly.interceptors.response.use(response => {
            //只将请求结果的data字段返回
            let res = response.data
            if (!is_online) {
                //   测试服打印
                console.log(res)
            }
            switch (res.status_code - 0) {
                case 1017:
                    wx.showToast({
                        title: res.message, //提示的内容,
                        icon: 'none', //图标,
                        duration: 1500, //延迟时间,
                        mask: true, //显示透明蒙层，防止触摸穿透,
                        success: res => {
                            setTimeout(() => {
                                wx.navigateTo({
                                    url: '/pages/package_mine/bind_tel/main'
                                })
                            }, 1500)
                        }
                    })
                    break
                case 1027:
                    wx.showToast({
                        title: res.message,
                        icon: 'none',
                        duration: 2000,
                        mask: true,
                        success () {
                            setTimeout(() => {
                                wx.navigateTo({
                                    url: '/pages/package_mine/identification/main'
                                })
                            }, 1500)
                        }
                    })
                    break
                case 1009:
                    wx.showToast({
                        title: res.message,
                        icon: 'none',
                        duration: 2000,
                        mask: true,
                        success () {
                            setTimeout(() => {
                                wx.removeStorage({
                                    key: 'user_token',
                                    success: res => {
                                        wx.navigateTo({ url: '/pages/package_main/login/main' });
                                    }
                                })
                            }, 1500)
                        }
                    })
                    break

                default:
                    break
            }
        })
        fly
            .post(path, data, isJava)
            .then(callback_success)
            .catch(err => {
                wx.hideLoading()
                console.log(err)
                wx.showToast({
                    title: '从前有个山，山里有个庙，庙里有个手机，网络出问题了！',
                    icon: 'none',
                    duration: 2000,
                    mask: false
                })
            })
    },
    $log (data) {
        if (!is_online) {
            console.log(data)
        }
    },
    to_detail (item) {
        let type = item.type
        let json_data = ''
        if (item.json_data) {
            json_data = JSON.parse(item.json_data)
        }
        console.log(item);

        switch (type) {
            case 1:
                //h5
                console.log(encodeURIComponent(item.links));

                wx.navigateTo({
                    url: `/pages/package_main/advertisement/main?url=${encodeURIComponent(item.links)}`
                })
                break
            case 2:
                //商品详情
                wx.navigateTo({
                    url: `/pages/package_mall/goods_detail/main?goods_id=${json_data.id}`
                })
                break
            case 3:
                //商品关键字搜索
                wx.navigateTo({
                    url: `/pages/package_main/searchPage/main?type=2&words=${json_data.field}`
                })
                break
            case 4:
                //签到
                wx.navigateTo({
                    url: `/pages/package_mine/sign_in/main`
                })
                break
            case 5:
                //跳转商品分类
                wx.navigateTo({
                    url: `/pages/package_projects/shop_type_detail/main?id=${json_data.id}`
                })
                break
            case 6:
                //项目详情
                wx.navigateTo({
                    url: `/pages/package_projects/project_detail/main?id=${json_data.id}`
                })
                break
            case 7:
                //跳转项目分类
                console.log(item.json_data);

                switch (json_data.project_cate_type) {
                    case 1:
                        // 一级分类
                        wx.navigateTo({ url: `/pages/package_projects/two_level/main?obj=${item.json_data}` });
                        break;
                    case 2:
                        // 二级分类
                        wx.navigateTo({ url: `/pages/package_projects/two_level/main?obj=${item.json_data}` });
                        break;
                    case 3:
                        // 三级分类
                        wx.navigateTo({ url: `/pages/package_projects/three_level/main?cate_name=${json_data.name}&cate_id=${json_data.id}` });
                        break;

                    default:
                        break;
                }
                break
            case 8:
                //项目关键字
                wx.navigateTo({
                    url: `/pages/package_main/search_index/main?status=2&keyword=${json_data.field}`
                })
                break
            case 9:
                // 商城首页
                wx.switchTab({
                    url: '/pages/shop_mall/main'
                })
                break
            case 10:
                // 品质医美首页
                wx.switchTab({ url: '/pages/beauty_mall/main' });
                break
            case 11:
                // 11 口腔馆首页
                wx.navigateTo({
                    url: '/pages/package_projects/oral/main?type=0'
                })
                break
            case 12:
                // 12 健康馆首页
                wx.navigateTo({
                    url: '/pages/package_projects/oral/main?type=-1'
                })
                break
            case 13:
                // 13 医美百科首页
                wx.switchTab({
                    url: '/pages/beauty_mall/main'
                })
                break
            case 14:
                // 14医生首页列表
                wx.navigateTo({
                    url: '/pages/package_projects/famousDoctors/main'
                })
                break
            case 15:
                // 15 医院首页列表
                wx.navigateTo({
                    url: '/pages/package_projects/hospital_list/main'
                })
                break
            case 16:
                // 小程序跳转
                wx.navigateTo({
                    url: item.links
                })
                break
            case 18:
                // 白玉美肤小程序
                wx.navigateToMiniProgram({
                    appId: 'wx836c6ce53dfc1176',
                    path: item.links,
                    envVersion: is_online ? 'release' : 'trial',
                    success (res) {
                        // 打开成功
                    }
                })

            case 19:
                // 美分享小程序
                wx.navigateToMiniProgram({
                    appId: 'wx2bc1e117355fd074',
                    path: item.links,
                    envVersion: is_online ? 'release' : 'trial',
                    success (res) {
                        // 打开成功
                    }
                })
                break     
                case 33:
                // 华视优选小程序
                wx.navigateToMiniProgram({
                    appId: 'wxfdc0b46f7d49b85d',
                    path: item.links,
                    envVersion: is_online ? 'release' : 'trial',
                    success (res) {
                        // 打开成功
                    }
                })
                break    
                 case 34:
                // 华悦口腔小程序
                wx.navigateToMiniProgram({
                    appId: 'wxc4081255550d1fcf',
                    path: item.links,
                    envVersion: is_online ? 'release' : 'trial',
                    success (res) {
                        // 打开成功
                    }
                })
                break   
                  case 35:
                // 美分享PLUS小程序
                wx.navigateToMiniProgram({
                    appId: 'wxa9677660ff805397',
                    path: item.links,
                    envVersion: is_online ? 'release' : 'trial',
                    success (res) {
                        // 打开成功
                    }
                })
                break
            case 100:
                // 新人专享礼
                wx.navigateTo({
                    url: `/pages/the_latest/main?url=${item.links}`
                })
                break
            case 26:
                // 邀请有礼
                wx.navigateTo({
                    url: `/pages/package_main/invitation_main/main?act_id=${json_data.id}`
                })
                break
            case 32:
                // 卡券商城
                wx.navigateTo({
                    url: `/pages/ct_store/store/main`
                })
                break

            default:
                // wx.showToast({
                //     title: '敬请期待', //提示的内容,
                //     icon: 'none', //图标,
                //     duration: 1000, //延迟时间,
                //     mask: false //显示透明蒙层，防止触摸穿透,
                // })
                break
        }
    },
    /**
     * loading
     * e {0:加载中，1：关闭加载中，2：showToast}
     * msg:showToast提示信息，必选，time，mask非必选默认1500，false
     */
    mmk_Loading (e, msg, time = 1500, mask = false) {
        switch (e) {
            case 0:
                wx.showLoading({
                    title: '加载中',
                    mask: true
                })
                break
            case 1:
                wx.hideLoading()
                break
            case 2:
                wx.showToast({
                    title: msg,
                    icon: 'none',
                    duration: time,
                    mask: mask
                })
                break
        }
    },
    mmk_toast ({ type = 0, msg, time = 1500, mask = false }) {
        switch (type) {
            case 0:
                wx.showLoading({
                    title: '加载中',
                    mask: true
                })
                break
            case 1:
                wx.showToast({
                    title: msg,
                    icon: 'none',
                    duration: time,
                    mask: mask
                })
                break
        }
    },
    //支付,暂时适用于商城
    wechat_pay (mall_name, order_sn, totalPrice, type = 'shop') {
        common.fly_post(
            'api/v4_5/payment/wechatpay_miniapp_submit',
            {
                //预支付
                openid: wx.getStorageSync('open_id'),
                body: mall_name,
                order_sn: order_sn,
                total: totalPrice,
                submit_type: (type == 1 || type == 2) ? 'shop' : type
            },
            response => {
                common.mmk_Loading(1)
                let res = response.data
                if (res.status_code == 0) {
                    wx.requestPayment({
                        timeStamp: res.data.timeStamp,
                        nonceStr: res.data.nonceStr,
                        package: res.data.package,
                        signType: 'MD5',
                        paySign: res.data.paySign,
                        success: function (res) {
                            wx.redirectTo({
                                url: `/pages/package_mall/mall_pay_success/main?order_price=${totalPrice}`
                            })
                        },
                        fail: function (res) {
                            if (type == 1) {
                                wx.redirectTo({
                                    url: '/pages/package_mine/my_order/main?type=1'
                                })
                            } else {
                                return false
                            }
                        }
                    })
                } else {
                    common.mmk_Loading(1)
                    common.mmk_Loading(2, res.message)
                }
            }
        )
    },
    //轮播图预览方法
    tapBigImg (banners, index) {
        let arr = []
        banners.forEach(el => {
            el = 'https://img.ameimeika.com/' + el
            arr.push(el)
        })
        wx.previewImage({
            current: 'https://img.ameimeika.com/' + banners[index], // 当前显示图片的http链接
            urls: arr
        })
    },
    //   微信登录
    mml_login () {
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo'] === true) {
                    // 已经授权，不会弹框
                    // 成功授权
                    if (wx.getStorageSync('user_token')) {
                        // 登陆了
                        that.url_path = 'mine'
                    } else {
                        // 没登陆
                        wx.showLoading({
                            title: '加载中', //提示的内容,
                            mask: true, //显示透明蒙层，防止触摸穿透,
                            success: res => { }
                        })
                        wx.login({
                            success: result => {
                                common.fly_post(
                                    'api/v4_5/minapp/login',
                                    {
                                        code: result.code,
                                        iv: e.mp.detail.iv,
                                        encryptedData: e.mp.detail.encryptedData,
                                        avatarUrl: e.mp.detail.userInfo.avatarUrl,
                                        nickName: e.mp.detail.userInfo.nickName,
                                        sid: this.sid
                                    },
                                    response => {
                                        wx.hideLoading()
                                        let res = response.data
                                        if (res.status_code == 0) {
                                            wx.setStorageSync('user_token', res.data.token)
                                            wx.setStorageSync('user_id', res.data.user_id)
                                            wx.setStorageSync('open_id', res.data.user_jwt)
                                            wx.removeStorage({
                                                key: 'pop_obj',
                                                success: res => { }
                                            })
                                            that.url_path = 'mine'
                                        } else {
                                            wx.hideLoading()
                                            wx.showToast({
                                                title: res.message,
                                                icon: 'none',
                                                duration: 2000,
                                                mask: false
                                            })
                                        }
                                    }
                                )
                            },
                            fail: () => {
                                wx.showToast({
                                    title: '登录失败', //提示的内容,
                                    icon: 'none', //图标,
                                    duration: 1500, //延迟时间,
                                    mask: true, //显示透明蒙层，防止触摸穿透,
                                    success: res => { }
                                })
                            }
                        })
                    }
                } else if (res.authSetting['scope.userInfo'] === false) {
                    // 授权弹窗被拒绝
                    wx.showToast({
                        title: '授权被禁用，请前往设置', //提示的内容,
                        icon: 'none', //图标,
                        duration: 2000, //延迟时间,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                        success: res => {
                            wx.openSetting({
                                success: res => { },
                                fail: res => { }
                            })
                        }
                    })
                } else {
                    // 没有弹出过授权弹窗
                    wx.authorize({
                        scope: 'scope.userInfo',
                        success: res => {
                            that.islogin = true
                            that.url_path = 'mine'
                        },
                        fail: () => { },
                        complete: () => { }
                    })
                }
            }
        })
    },
    // 跳转合力客服

    // 保存图片
    save_poster (img_url) {
        console.log(img_url + '----508')
        wx.downloadFile({
            url: img_url, //仅为示例，并非真实的资源
            success: function (res) {
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success (res) {
                            wx.showToast({
                                title: "图片保存成功", //提示的内容,
                                icon: "success", //图标,
                                duration: 2000, //延迟时间,
                                mask: true, //显示透明蒙层，防止触摸穿透,
                                success: res => { }
                            });
                        },
                        fail (res) {
                            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                                // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
                                wx.showModal({
                                    title: '提示',
                                    content: '需要您授权保存相册',
                                    showCancel: false,
                                    success: modalSuccess => {
                                        wx.openSetting({
                                            success (settingdata) {
                                                console.log("settingdata", settingdata)
                                                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                    wx.showModal({
                                                        title: '提示',
                                                        content: '获取权限成功,再次即可保存',
                                                        showCancel: false,
                                                    })
                                                } else {
                                                    wx.showModal({
                                                        title: '提示',
                                                        content: '获取权限失败，将无法保存到相册哦~',
                                                        showCancel: false,
                                                    })
                                                }
                                            },
                                            fail (failData) {
                                                console.log("failData", failData)
                                            },
                                            complete (finishData) {
                                                console.log("finishData", finishData)
                                            }
                                        })
                                    }
                                })
                            }
                        }
                    });
                }
            }
        });
    },
    // 保存视频
    save_video (img_url) {
        console.log(img_url + '----509')
        wx.downloadFile({
            url: img_url, //仅为示例，并非真实的资源
            success: function (res) {
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                    wx.saveVideoToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success (res) {
                            wx.showToast({
                                title: "视频保存成功", //提示的内容,
                                icon: "success", //图标,
                                duration: 2000, //延迟时间,
                                mask: true, //显示透明蒙层，防止触摸穿透,
                                success: res => { }
                            });
                        },
                        fail (res) {
                            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                                // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
                                wx.showModal({
                                    title: '提示',
                                    content: '需要您授权保存相册',
                                    showCancel: false,
                                    success: modalSuccess => {
                                        wx.openSetting({
                                            success (settingdata) {
                                                console.log("settingdata", settingdata)
                                                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                    wx.showModal({
                                                        title: '提示',
                                                        content: '获取权限成功,再次点击即可保存',
                                                        showCancel: false,
                                                    })
                                                } else {
                                                    wx.showModal({
                                                        title: '提示',
                                                        content: '获取权限失败，将无法保存到相册哦~',
                                                        showCancel: false,
                                                    })
                                                }
                                            },
                                            fail (failData) {
                                                console.log("failData", failData)
                                            },
                                            complete (finishData) {
                                                console.log("finishData", finishData)
                                            }
                                        })
                                    }
                                })
                            }
                        }
                    });
                }
            }
        });
    },
    // 合成图片
    getImg (type, item_id, model, src) {
        wx.showLoading({
            title: "", //提示的内容,
            mask: true, //显示透明蒙层，防止触摸穿透,
            success: res => { }
        });
        common.fly_post(
            "api/v4_5/image/share_qrcode",
            {
                type: type,   // type 2项目 3商品 26服务 27会员卡详情   
                item_id: item_id,   //项目id  或者商品id
                user_id: wx.getStorageSync("user_id") || 0,
                model: model,   //样式 123456
                src: src   //二维码链接
            },
            response => {
                wx.hideLoading();
                let res = response.data;
                if (res.status_code == 0) {
                    // console.log(res.data.qrcode+'----999')
                    this.save_poster(res.data.qrcode)
                    //   return res.data.qrcode;

                } else {
                    common.mmk_Loading(2, res.message);
                }
            }
        );
    },
    // 跳转客服
    to_service () {
        wx.navigateTo({ url: '/pages/package_mine/heli_service/main' });
    },
    // 卡券订单跳转客服
    ct_service (order_id = 0) {
        // order_id 订单的id
        wx.navigateTo({ url: `/pages/ct_store/heli_service/main?orderId=${order_id}` });
    }
}

export default common


